<?php
class Users extends CI_Model{

        function __construct(){
            parent::__construct();
        }
		
        /**
         * 
         * Login korisnika
         * @param string $email - mail adresa
         * @param string $passw - MD5 kriptovani password
         */
        public function loginUser($email,$passw)
        {
        	$sql =" SELECT `id`,`firstname` , `lastname` , `email` 
        			FROM `site_user`
        			WHERE `email` = '{$email}' AND `password` = '{$passw}'; ";
        	$result = $this->db->query($sql);
        	
        	
        	if($result->num_rows())
        	{
        		$user_data = $result->row();
        		
        		$this->session->set_userdata('site_user_id', $user_data->id);
        		$this->session->set_userdata('firstname', $user_data->firstname);
        		$this->session->set_userdata('lastname', $user_data->lastname);
        		$this->session->set_userdata('email', $user_data->email);
        		$this->session->set_userdata('is_logged', true);
        		
        		//Upisi kad je logovan i IP adresu
        		$sql = "UPDATE `site_user` SET `lastlogin` = ".time().", `lastip` = '".$this->input->ip_address()."'
        				WHERE `id` = ".$user_data->id." ; ";
        				
        		$this->db->query($sql);
        		
        		return true;
        	}
        	else
        		return false;
        }
        
        public function insertUser($post)
        {
        	$sql = "INSERT INTO `site_user` (`firstname` , `lastname` , `email` , `password` , `created` , `email_confirm`)
        			VALUES ('{$post['firstname']}','{$post['lastname']}','{$post['email']}','{$post['passw']}',".time().",0);        			 
        		";
        	$this->db->query($sql);
        	
        	return $this->db->affected_rows();
        }
        
        public function emailCheck($email)
        {
        	$sql = "SELECT email FROM `site_user` WHERE `email` = '{$email}';";
        	$result = $this->db->query($sql);
        	return $result->num_rows();
        }
        
        /*
         * 	Potvrda registracije
         *  @param string $email - MD5 kriptovana email adresa
         */
        public function userConfirm($email)
        {
        	$sql = "UPDATE `site_user` SET `email_confirm` = 1 WHERE MD5(`email`) = '{$email}'; ";
        	//echo $sql;
        	$this->db->query($sql);
        	//echo $this->db->affected_rows();
        	return $this->db->affected_rows();
        }
        
}